﻿var map;
var infoWindow;
var service;
var bound;

$(function () {
    var progressbar = $("#progressbar"),
      progressLabel = $(".progress-label");

    progressbar.progressbar({
        value: false,
        change: function () {
            progressLabel.text(progressbar.progressbar("value") + "%");
        },
        complete: function () {
            progressLabel.text("Complete!");
        }
    });

    //setTimeout( progress, 1 );
});
function progress() {
    var progressbar = $("#progressbar");
    var val = progressbar.progressbar("value") || 0;

    progressbar.progressbar("value", val + 1);

    if (val < 99) {
        setTimeout(progress, 40);
    } else {
        $('#button_new').removeAttr('disabled');
        if (ii < resultzzz.length)
            onclickNewButton();
        else
            $("#loading").html("Loading Completed ! (" + ii.toString() + "/" + resultzzz.length.toString() + ")");
    }
}

function initialize() {
    map = new google.maps.Map(document.getElementById('map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(parseFloat($("#text_lat").val()), parseFloat($("#text_lng").val())),
    zoom: parseInt($("#text_zoom").val()),
        //styles: [
          //{
            //stylers: [
              //{ visibility: 'simplified' }
            //]
          //},
          //{
            //elementType: 'labels',
            //stylers: [
              //{ visibility: 'off' }
            //]
          //}
        //]
    });

    infoWindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(map);

    google.maps.event.addListener(map, "bounds_changed", function() {
        bound = map.getBounds();
    });
	
    var input = document.getElementById('searchTextField');
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);
           
    var infowindowz = new google.maps.InfoWindow();
    var markerz = new google.maps.Marker({
        map: map
    });
           
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        infowindowz.close();
        markerz.setVisible(false);
        input.className = '';
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            // Inform the user that the place was not found and
            input.className = 'notfound';
            return;
        }
         
        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  // Why 17? Because it looks good.
        }
        markerz.setIcon(/** @type {google.maps.Icon} */({
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        markerz.setPosition(place.geometry.location);
        markerz.setVisible(true);
         
        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
         
        infowindowz.setContent('<div><strong>' + place.name + '</strong><br>' + address);
        infowindowz.open(map, markerz);
    });
}

function performSearch() {
  var request = {
    bounds: bound,
    keyword: $("#text_type").val()
  };
  service.radarSearch(request, callback);
}

var list = new Array();

function MyObject(lat, lng, icon, name, rating, vicinity, phoneNumber, address, url, website, addressNumber){
	this.lat = lat;
	this.lng = lng;
	this.icon = icon;
	this.name = name;
	this.rating = rating;
	this.vicinity = vicinity;
	this.phoneNumber = phoneNumber;
	this.address = address;
	this.url = url;
	this.website = website;
    this.addressNumber = addressNumber;
}

 function converttoascii(mystr)
 {
	var s = mystr;

            var VietnameseSigns = new Array();
           
               VietnameseSigns[0]= "aAeEoOuUiIdDyY";
                VietnameseSigns[1]="áàạảãâấầậẩẫăắằặẳẵ";
                VietnameseSigns[2]="ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ";
                VietnameseSigns[3]="éèẹẻẽêếềệểễ";
               VietnameseSigns[4]= "ÉÈẸẺẼÊẾỀỆỂỄ";
                VietnameseSigns[5]="óòọỏõôốồộổỗơớờợởỡ";
                VietnameseSigns[6]="ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ";
               VietnameseSigns[7]= "úùụủũưứừựửữ";
               VietnameseSigns[8]= "ÚÙỤỦŨƯỨỪỰỬỮ";
                VietnameseSigns[9]="íìịỉĩ";
                VietnameseSigns[10]="ÍÌỊỈĨ";
               VietnameseSigns[11]= "đ";
               VietnameseSigns[12]= "ĐÐ";
                VietnameseSigns[13]="ýỳỵỷỹ";
               VietnameseSigns[14]= "ÝỲỴỶỸ" ;


            for (var i = 1; i < VietnameseSigns.length; i++)
                for (var j = 0; j < VietnameseSigns[i].length; j++)
{
			var str =VietnameseSigns[i][j];

                    s = s.split(str).join(VietnameseSigns[0][i - 1]);

}


           s = s.replace(/ /g, '');
            return s.toLowerCase();
 }

function loadIntoLayout(){
	var html = "";
	
	for(var i = 0;i<list.length;i++){
  	    var s=converttoascii(list[i].address);
	    var t =converttoascii($("#text_street").val());
	    if(s.toLowerCase().indexOf(t.toLowerCase())!=-1){
	    	//Ajax list[i] này lên server để insert vô db
		    html +="<tr><td>"+(i+1).toString()+"</td><td>"+list[i].name+"</td><td>"+list[i].addressNumber+"</td><td>"+list[i].lat.toFixed(6)+"</td><td>"+list[i].lng.toFixed(6)+"</td>";
			    if(list[i].phoneNumber != null){
				    html += "<td>" + list[i].phoneNumber+"</td>";
			    } else {
				    html += "<td>" + ""+"</td>";
			    }
			    if(list[i].website != null){
				    html += "<td>"+list[i].website+"</td></tr>";
			    } else {
				    html += "<td>" + ""+"</td>";
			    }
        }
    }
	
	return html;
}

function onclickButton(){
	//initialize();
	clearOverlays();
	performSearch();
}
var ii = 0;
function onclickNewButton(){

	$("#loading").html("Auto load detail places ("+ii.toString()+"/"+resultzzz.length.toString()+")...");
	 $('#button_new').attr('disabled','disabled');
	
	var progressbar = $( "#progressbar" );
	progressbar.progressbar( "value", 0 );	
		
	setTimeout( progress, 1 );
	
	for(var i = 0;i<10;i++){
		getDetailOfPlace(resultzzz[ii]);
		if(flag == false){
			flag = true;
			return;
		}
		ii++;
	}	
}

var resultzzz;
var flag = true;

function checkStringContainNumber(value){
    var matches = value.match(/\d+/g);
    if (matches != null) {
        return true;
    }
    return false;
}
function getDetailOfPlace(place){
	service.getDetails(place, function(result, status) {
		  if (status != google.maps.places.PlacesServiceStatus.OK) {
		   // alert(status);
		   flag = false;
			return;
		  }
		  if(result){
			  var temp = new MyObject();
			  temp.lat = result.geometry.location.ob;
			  temp.lng = result.geometry.location.pb;
			  temp.icon = result.icon;
			  temp.name = result.name;
			  temp.rating = result.rating;
			  temp.vicinity = result.vicinity;
			  temp.phoneNumber = result.international_phone_number;
              if(checkStringContainNumber(result.address_components[0].long_name)){
                temp.addressNumber = result.address_components[0].long_name;
              }else{
                temp.addressNumber = result.formatted_address.substring(0, result.formatted_address.indexOf(" "));
                firstSemiColonIndex = temp.addressNumber.indexOf(",");
                if(firstSemiColonIndex >= 0){
                    temp.addressNumber = temp.addressNumber.substring(0, temp.addressNumber.indexOf(","));
                }
              }
			  
              temp.address = result.formatted_address;
			  temp.url = result.url;
			  temp.website = result.website;
			  list.push(temp);
			  
			  
		
			$("table").find("tr:gt(0)").remove();
			$("#table").append(loadIntoLayout());
			
		  }
		});
}

function callback(results, status) {
	resultzzz = results;
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }
  for (var i = 0, resultz; resultz = results[i]; i++) {
    createMarker(resultz);
  }
  var html = loadIntoLayout();
  $("#table").append(html);
  list.splice(0,list.length);
	$("table").find("tr:gt(0)").remove();
	ii=0;
	
	$("#total").html("Total: " + resultzzz.length.toString() + " places");
	
	
}
var markersArray = [];

function clearOverlays() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: {
      // Star
      path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
      fillColor: '#ffff00',
      fillOpacity: 1,
      scale: 1/4,
      strokeColor: '#bd8d2c',
      strokeWeight: 1
    }
  });
	markersArray.push(marker);
  google.maps.event.addListener(marker, 'click', function() {
    service.getDetails(place, function(result, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
      }
      infoWindow.setContent(result.name);
      infoWindow.open(map, marker);
    });
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
